import * as THREE from 'three';
const loader = new THREE.FileLoader();
import {lon2xyz} from "./math.js"
loader.setResponseType('json');
const lineGroup = new THREE.Group();
const model = new THREE.Group();
//加载一个文本文件，并把结果输出到控制台上
loader.load('/world.json',function ( data ) {
  data.features.forEach((area) => {
  // coordinates数据分为单组和多组，将单组的封装为多组
    if(area.geometry.type === 'Polygon'){
        area.geometry.coordinates = [area.geometry.coordinates]
    }
    lineGroup.add(moreLine(area.geometry.coordinates)) 
  });
})
var R = 100
const geometry = new THREE.SphereGeometry( R, 32, 16 );
const texture = new THREE.TextureLoader().load( '/earth.png');
const material = new THREE.MeshBasicMaterial( { map:texture });
const sphere = new THREE.Mesh( geometry, material );
model.add( sphere,lineGroup );
const materialLine = new THREE.LineBasicMaterial({
  color: 0x004444
});
// 批量产生线框
const moreLine = (coordinates)=>{
  const groupLine = new THREE.Group();
  coordinates.forEach(polygon=>{
    groupLine.add(oneLine(polygon[0])) 
  })
  return groupLine;
}
// 产生单个线框
const oneLine = (pointArr)=>{
  const points = [];
  pointArr.forEach(item=>{
    var point = lon2xyz(R,item[0],item[1]);
    points.push(new THREE.Vector3(point.x,point.y,point.z));
  })
  const geometry = new THREE.BufferGeometry().setFromPoints( points );
  const line = new THREE.Line( geometry, materialLine );
  line.position.x += 0.1;
  line.position.y += 0.1;
  line.position.z += 0.1;
  return line;
}
export {model};